<?php
/**  
 * HTTP::Response
 *  
 * @copyright  2009 Orb71.com  
 * @license    ?  
 * @version    Release: @package_version@  
 * @link       ?  
 */  
class HTTP_Response {
    public $data    = '';
    public $code    = '';
    public $headers = array();

    public function __construct($args=array())
    {
        foreach($args as $prop => $val) {
            $this->$prop = $val;
        }
    }

    public function isError()
    {
        // Probably not an error
        if($this->code && $this->code < 400)
            return false;
       
        return true;
    }

    public function getAWS3error()
    {
        if($this->isError()) {
            // Now we have an error.
            $x = new SimpleXMLElement($this->data);
            return (array)$x;
        }
    }

    public function curlwritefunc($curl, $data)
    {
        $this->data .= $data;
        return strlen($data);
    }

    public function curlheaderfunc($curl, $data)
    {
        $headers = preg_split('/[\r\n]+/',$data); 
        foreach($headers as $h) {
            $h = trim($h);
            if(preg_match('/^([A-Za-z0-9][^:]+)\s*:\s*(.+)$/',$h,$match)) {
                $this->headers[strtolower($match[1])] = $match[2];
            }
        }

        return strlen($data);
    }

    public function getMeta($meta)
    {
        foreach($this->headers as $key => $val) {
            if(preg_match("/^x-amz-meta-$meta$/i",$key)) {
                return $val;
            }
        }
    }

    /**
     * Don't use this function with CURLOPT_USERPWD
     * Actually, build the response header by issuing a head request
     */
    public function curlToBrowserheaderfunc($curl, $data)
    {
        $headers = preg_split('/[\r\n]+/',$data); 

        foreach($headers as $h) {
            $h = trim($h);
            if(preg_match('/^([A-Za-z0-9][^:]+)\s*:\s*(.+)$/',$h)) {
                header($h);            
            }
        }

        return strlen($data);
    }
}


